# SCHEDULE SCRIPT
# This script generates the regular season schedule for the
# provided league round-robin style.
#
# Created on December 5, 2009 by Caleb Goff

#!/bin/bash
set +x

# Retrieve team IDs for the given league
mysql FBT52009 -p$1 -horion.csl.mtu.edu > file2.txt <<EOFMYSQL
SELECT TEAM_ID FROM TEAMS WHERE LEAGUE_ID = '$2'
EOFMYSQL

count=0
league=$2
declare -a ARRAY

# Load the IDs into an array for scheduling purposes
for line in $(sed '1d' file2.txt)
do  
    echo $count
    ARRAY[($count)]=$line
    ((count++))
done

even=$((count%2))

if [ $even -gt 0 ] ; then
    ARRAY[($count)]=0
fi

# Cycle through the array and schedule the first round
ELEMENTS=${#ARRAY[@]}

# Check if we have an even number of teams or not
# $even = 0 means we have even number, $even = 1 means odd number of teams
even=$(($ELEMENTS%2))

week=1

for (( j=0;j<(8);j++)); do
    
    echo
    echo Week $week
    
    #print games
    for (( i=0;i<$ELEMENTS;i=i+2)); do
        home=${ARRAY[i]}
        away=${ARRAY[i+1]}
        
        #debug information
        echo pair $home - $away

    done

    #increment week
    ((week++))
    old=0

    #rotate teams in schedule
    for (( k=2;k<$ELEMENTS;k++)); do

        ((temp=$ELEMENTS-1))
    
        echo k = $k
        echo size = $ELEMENTS
        echo temp = $temp

        if [ $k -lt $temp ] ; then
            if [ $old -gt 0 ] ; then
                echo one swap                
                temp=${ARRAY[k]}
                ARRAY[k]=$old
                old=$temp
                echo old $old
            else
                echo two swap
                start=${ARRAY[k-1]}
                old=${ARRAY[k]}
                ARRAY[k]=$start
                echo start $start
                echo old $old
                echo ${ARRAY[0]}
                echo ${ARRAY[1]}
                echo ${ARRAY[2]}
            fi
        else
            echo my three swap
            temp=${ARRAY[k]}
            ARRAY[k]=$old
            ARRAY[1]=$temp
        fi
        
    done

    echo

done

rm -f file2.txt
